import { useState, useEffect } from 'react';
import style from './style.module.scss';
import {
  Popconfirm, Spin, Table, Form, Input, InputNumber, DatePicker,
  Modal, Radio, message, Button, Space, Tag
} from 'antd';
import type { PaginationProps, TableProps } from 'antd';
import axios from 'axios';
import { STORE_TAG_COLOR, STORE_TYPE_COLOR, StoreTagOptions } from "@/config/storeConfig";
import type { BasicInfo, StoreTag, StoreType } from "@/Interface/StoreInfoInterface";
import dayjs, { Dayjs } from 'dayjs';
import { generateStoreId } from '@/api/mockData/mockStoreData';
import http from '@/api/axios';


// 表单类型接口
interface CreateStoreForm {
  storeName: string;
  province: string;
  city: string;
  lng: string;
  lat: string;
  storeType: string;
  areaSize: number;
  openingDate: Dayjs;
  tags: string;
}


export default function StoreDetail() {
  const [data, setData] = useState<BasicInfo[]>();
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 8, total: 0 });
  const [form] = Form.useForm<CreateStoreForm>();
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [currentStore, setCurrentStore] = useState<BasicInfo | null>(null);
  const [searchKeyword, setSearchKeyword] = useState('');

  // 每次打开编辑弹窗时，重置表单并设置新值
  useEffect(() => {
    form.resetFields();
    if (editModalVisible && currentStore) {
      form.setFieldsValue(transformStoreData(currentStore));
    }
  }, [editModalVisible, currentStore]); // 依赖弹窗状态和当前数据

  // 提交表单
  const handleSubmitStore = async (values: any) => {
    try {
      setConfirmLoading(true);
      // 生成或获取门店ID
      const storeId = currentStore ? currentStore.storeId : generateStoreId();

      // 构建请求数据
      const storeData = {
        basicInfo: {
          storeId: storeId,
          storeName: values.storeName,
          province: values.province,
          city: values.city,
          coordinates: {
            lng: values.lng,
            lat: values.lat
          },
          storeType: values.storeType,
          areaSize: Number(values.areaSize),
          openingDate: values.openingDate.format('YYYY-MM-DD'),
          tags: [values.tags]
        }
      };

      // 判断请求类型
      const isUpdate = !!currentStore;
      const request = isUpdate
        ? http.put(`/api/stores/${storeId}`, storeData)
        : http.post('/api/stores', storeData);

      // 执行请求
      await request;

      // 处理成功结果
      message.success(isUpdate ? '修改成功' : '创建成功');

      // 关闭模态框
      setCreateModalVisible(false);
      setEditModalVisible(false);
      form.resetFields();

      // 刷新数据
      getData(pagination.current, pagination.pageSize);
    } catch (error) {
      console.error(error);
      message.error(currentStore ? '修改失败' : '创建失败');
    } finally {
      setConfirmLoading(false);
      setCurrentStore(null); // 清除编辑状态
    }
  };

  // 处理删除
  const handleDelete = async (storeId: string) => {
    try {
      // 调用删除门店接口
      await http.delete(`/api/stores/${storeId}`)
      message.success('删除成功')
      // 刷新表格数据
      getData(pagination.current, pagination.pageSize);

    } catch (error) {
      console.log(error);
      message.error('删除失败')
    }
  }

  // 转换表格数据为表单格式
  const transformStoreData = (store: BasicInfo) => ({
    ...store,
    openingDate: dayjs(store.openingDate),
    lng: store.coordinates.lng,
    lat: store.coordinates.lat,
    tags: store.tags[0]
  });

  // 自定义分页器
  const customItemRender: PaginationProps['itemRender'] = (
    currentPage,
    type,
    originalElement
  ) => {
    if (type === 'jump-prev' || type === 'jump-next') {
      return null; // 不渲染跳转按钮
    }
    if (type === 'page') {
      const totalPages = Math.ceil(pagination.total / pagination.pageSize);
      let start = 1;
      let end = totalPages;

      if (totalPages > 5) {
        start = Math.max(1, pagination.current - 2);
        end = Math.min(totalPages, pagination.current + 2);
        if (pagination.current <= 3) {
          end = 5;
        } else if (pagination.current >= totalPages - 2) {
          start = totalPages - 4;
        }
      }

      return (currentPage >= start && currentPage <= end) ? originalElement : null;
    }
    return originalElement;
  };


  // 获取分页数据
  const getData = async (page = 1, pageSize = 8, keyword = searchKeyword) => {
    setLoading(true);
    try {
      // 根据搜索状态选择接口
      const url = keyword ? '/api/stores/search' : '/api/stores/paged';
      // 统一请求参数
      const params = {
        page,
        pageSize,
        ...(searchKeyword && { keyword: searchKeyword })
      };

      const res = await axios.get(url, { params });
      // 统一数据结构处理
      const responseData = searchKeyword
        ? { list: res.data.data.list, pagination: res.data.data.pagination }
        : res.data.data;

      // 空结果提示（仅搜索时触发）
      if (searchKeyword && responseData.list.length === 0) {
        message.config({ top: 40, duration: 2, maxCount: 1 });
        const tips = () => message.open({ type: 'info', content: '未匹配到结果' });
        tips();
        return;
      }

      setData(responseData.list);
      setPagination(prev => ({
        ...prev,
        current: page,
        pageSize,
        total: responseData.pagination.total
      }));

    } catch (error) {
      const errorMsg = searchKeyword ? '搜索失败' : '数据获取失败';
      message.error(errorMsg);
      console.error(errorMsg, error);
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    getData(pagination.current, pagination.pageSize);
  }, []);

  // 分页变化回调
  const handleTableChange = (pagination: any) => {
    getData(pagination.current, pagination.pageSize);
  };


  // // 处理搜索
  const handleSearch = (value: string) => {
    // 直接获取当前输入框的值，而不是 searchKeyword 状态
    const keyword = value.trim();

    if (keyword) {
      // 更新状态并执行搜索
      setSearchKeyword(keyword);
      getData(1, pagination.pageSize, keyword);
    }
  };

  // 处理返回
  const handleBack = () => {
    setSearchKeyword('');
    getData(1, pagination.pageSize, '');
  };


  // 调整 columns 定义以匹配 Mock 数据字段
  const columns: TableProps<BasicInfo>['columns'] = [
    {
      title: '门店标识',
      dataIndex: 'storeId',
      key: 'storeId',
      width: '13%',
    },
    {
      title: '门店名称',
      dataIndex: 'storeName',
      key: 'storeName',
      width: '20%',
    },
    {
      title: '类型',
      dataIndex: 'storeType',
      key: 'storeType',
      width: '10%',
      render: (type) => (
        <Tag color={STORE_TYPE_COLOR[type as StoreType]}>
          {type}
        </Tag>
      ),
    },
    {
      title: '省份/城市',
      key: 'location',
      width: '20%',
      render: (_, record) => `${record.province} / ${record.city}`,
    },
    {
      title: '开业日期',
      dataIndex: 'openingDate',
      key: 'openingDate',
      width: '13%',
    },
    {
      title: '标签',
      key: 'tags',
      dataIndex: 'tags',
      width: '12%',
      render: (tags: string[]) => (
        <>
          {tags.map((tag: string) => (
            <Tag color={STORE_TAG_COLOR[tag as StoreTag]} key={tag}>
              {tag}
            </Tag>
          ))}
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: '13%',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type='primary'
            onClick={() => {
              setCurrentStore(record);
              setEditModalVisible(true);
            }}
          >
            修改
          </Button>
          <Popconfirm
            className={style.popconfirm}
            title="提示"
            description="此操作将彻底删除该门店，是否确认？"
            okText="确认"
            cancelText="取消"
            placement='topRight'
            onConfirm={() => handleDelete(record.storeId)}
          >
            <Button type='primary'>删除</Button>
          </Popconfirm>
        </Space >
      ),
    },
  ];

  const { Search } = Input;

  return (
    <div className={style.info}>
      <div className={style.top}>
        <p>当前门店数：{pagination.total}</p>
        <div className={style.search}>
          <Search
            placeholder="输入门店名称或ID"
            enterButton={true}
            value={searchKeyword}
            onSearch={handleSearch}
            onChange={(e) => setSearchKeyword(e.target.value)}
            allowClear
          />
          <Button type='primary' onClick={handleBack}>返回</Button>
        </div>
        <div className={style.btn}>
          <Button
            type='primary'
            onClick={() => setCreateModalVisible(true)}
          >
            新增门店
          </Button>
        </div>
      </div>

      <Modal
        title={currentStore ? "修改门店" : "新建门店"}
        open={createModalVisible || editModalVisible}
        onOk={() => form.submit()}
        onCancel={() => {
          setCreateModalVisible(false);
          setEditModalVisible(false);
          form.resetFields();
        }}
        confirmLoading={confirmLoading}
        afterClose={() => {
          form.resetFields();
          setCurrentStore(null);
        }}  //重置表单
        centered={false}
        style={{ top: '5vh' }}
        okText="确认"
        cancelText="取消"
        forceRender  // 预渲染 Form 组件
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmitStore}
        >
          {/* 门店名称 */}
          <Form.Item
            label="门店名称"
            name="storeName"
            rules={[
              { required: true, message: '请输入门店名称' },
              { max: 30, message: '名称不能超过50个字符' }
            ]}
          >
            <Input placeholder="请输入门店名称" />
          </Form.Item>

          {/* 类型 */}
          <Form.Item
            label="门店类型"
            name="storeType"
            rules={[{ required: true, message: '请选择门店类型' }]}
            className={style.formItem}
          >
            <Radio.Group>
              <Radio value="直营">直营</Radio>
              <Radio value="加盟">加盟</Radio>
            </Radio.Group>
          </Form.Item>

          {/* 地理位置 */}
          <div className={style.formRow}>
            <Form.Item
              label="省份"
              name="province"
              rules={[
                { required: true, message: '请输入省份' },
                { pattern: /^[\u4e00-\u9fa5]{2,10}$/, message: '请输入2-10个中文字符' }
              ]}
              className={style.formItem}
            >
              <Input
                placeholder="例如：北京市"
                allowClear
                showCount
                maxLength={10}
              />
            </Form.Item>

            <Form.Item
              label="城市"
              name="city"
              rules={[
                { required: true, message: '请输入城市' },
                { pattern: /^[\u4e00-\u9fa5]{2,10}$/, message: '请输入2-10个中文字符' }
              ]}
              className={style.formItem}
            >
              <Input
                placeholder="例如：朝阳区"
                allowClear
                showCount
                maxLength={10}
              />
            </Form.Item>
          </div>

          {/* 经纬度 */}
          <div className={style.formRow}>
            <Form.Item
              label="经度"
              name="lng"
              rules={[
                { required: true, message: '请输入经度' },
                { pattern: /^-?\d+(\.\d+)?$/, message: '请输入有效经度' }
              ]}
              className={style.formItem}
            >
              <Input placeholder="例如：116.404" />
            </Form.Item>

            <Form.Item
              label="纬度"
              name="lat"
              rules={[
                { required: true, message: '请输入纬度' },
                { pattern: /^-?\d+(\.\d+)?$/, message: '请输入有效纬度' }
              ]}
              className={style.formItem}
            >
              <Input placeholder="例如：39.915" />
            </Form.Item>
          </div>

          {/* 标签 */}
          <Form.Item
            label="门店标签"
            name="tags"
            rules={[{ required: true, message: '请选择门店标签' }]}
          >
            <Radio.Group>
              {StoreTagOptions.map(tag => (<Radio value={tag} key={tag} >{tag}</Radio>))}
            </Radio.Group>
          </Form.Item>

          <div className={style.formRow}>
            {/* 开业日期 */}
            <Form.Item
              label="开业日期"
              name="openingDate"
              rules={[{ required: true, message: '请选择开业日期' }]}
            >
              <DatePicker
                format="YYYY-MM-DD"
                style={{ width: '100%' }}
                disabledDate={current => current && current > dayjs().endOf('day')}
              />
            </Form.Item>

            {/* 面积 */}
            <Form.Item
              label="门店面积（㎡）"
              name="areaSize"
              rules={[
                { required: true, message: '请输入门店面积' },
                { type: 'number', min: 10, max: 10000 }
              ]}
              className={style.formItem}
            >
              <InputNumber min={10} max={10000} step={10} style={{ width: '100%' }} />
            </Form.Item>
          </div>
        </Form>
      </Modal>

      {data ? (
        <Table
          columns={columns}
          dataSource={data}
          rowKey="storeId"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: false,
            position: ['bottomCenter'],
            itemRender: customItemRender,
            showQuickJumper: true
          }}
          onChange={handleTableChange}
        />
      ) : (
        <Spin />
      )}
    </div>
  );
}



